// useEvent.ts
import { getCurrentInstance, onUnmounted } from 'vue';
import { eventManager } from './eventManager';

export function useEvent() {
	const instance = getCurrentInstance()?.proxy;

	const validateInstance = () => {
		if (!instance) {
			console.warn('useEvent 必须在 Vue 组件的 setup() 函数内使用');
			return false;
		}
		return true;
	};

	/** 事件注册 */
	const eventOn = <T = any>(eventName: string, callback: (payload?: T) => void) => {
		if (!validateInstance()) return;

		try {
			eventManager.on(eventName, callback, instance);
		} catch (error) {
			console.error('事件注册失败:', error);
		}
	};

	/** 事件注销 */
	const eventOff = (eventName: string, callback: (payload?: any) => void) => {
		if (!validateInstance()) return;

		try {
			eventManager.off(eventName, callback, instance);
		} catch (error) {
			console.error('事件注销失败:', error);
		}
	};

	/** 事件触发 */
	const eventEmit = (eventName: string, ...args: any[]) => {
		try {
			eventManager.emit(eventName, ...args);
		} catch (error) {
			console.error('事件触发失败:', error);
		}
	};

	/** 事件清空 */
	const eventUnsubscribeAll = () => {
		try {
			eventManager.unsubscribeAll(instance);
		} catch (error) {
			console.error('事件清空失败:', error);
		}
	};

	// 事件订阅调试方法
	const logEventSubscriptions = (targetEvent?: string) => {
		const debugInfo = eventManager.getSubscriptions(targetEvent);
		console.groupCollapsed('[全局事件] 订阅信息');
		console.table(debugInfo.map(info => ({
			事件名称: info.eventName,
			订阅数量: info.subscriptionCount,
			组件实例: info.subscribers.map(s => s.instance?.$options.name || '匿名组件')
		})));
		console.groupEnd();
	};

	// 实例订阅调试方法
	const logInstanceSubscriptions = () => {
		if (!validateInstance()) return;

		const subscriptions = eventManager.getInstanceSubscriptions(instance);
		const componentName = instance?.$options.name || '匿名组件';

		console.groupCollapsed(`[实例事件] ${componentName} 的订阅`);
		if (subscriptions.length === 0) {
			console.log('该组件未订阅任何事件');
		} else {
			console.table(subscriptions.map(sub => ({
				事件名称: sub.eventName,
				回调函数: sub.callbackNames.join(', ') || '匿名函数',
				订阅时间: new Date().toLocaleTimeString()
			})));
		}
		console.groupEnd();
	};

	// 自动清理
	onUnmounted(() => {
		eventUnsubscribeAll();
	});

	return {
		eventOn,
		eventOff,
		eventEmit,
		eventUnsubscribeAll,
		logEventSubscriptions,
		logInstanceSubscriptions
	};
}